package utils
{
	
	import flash.display.Loader;
	import flash.net.FileFilter;
	import flash.net.FileReference;
	import flash.events.*;
	/**
	 * ...
	 * @author Dmitriy Gaiduk
	 */
	
	 /**
	 * When loader copmlete. If there is error, property error is not empty
	 * @eventType flash.events.Event
	 */
	[Event(name = "complete", type = "flash.events.Event")]
	
	public class ImageChooser extends EventDispatcher
	{
		private var _fileRef:FileReference;
		private var _imgLoader:Loader;
		private var _fileFilter:FileFilter;
		private const IMG_SIZE_Bytes:Number = 1048576 * 2;
		private var _content:Object;
		public var errors:String;
		
		public function ImageChooser() 
		{
			_fileRef = new FileReference();
			_fileRef.addEventListener(Event.SELECT, onFileSelected);
			_fileRef.addEventListener(Event.CANCEL, onCancel);
			_fileRef.addEventListener(IOErrorEvent.IO_ERROR, onIOError);
			_fileRef.addEventListener(SecurityErrorEvent.SECURITY_ERROR, onSecurityErr);
			_fileFilter = new FileFilter("Image files (*.jpeg, *.png)", "*.jpeg; *.jpg; *.png");
		}
		
		public function Browse():void
		{
			_fileRef.browse([_fileFilter]);
		}
		
		private function onSecurityErr(e:SecurityErrorEvent):void 
		{
			errors += "SecurityErr: " + e.text;
			trace("Security err");
		}
		
		private function onIOError(e:IOErrorEvent):void 
		{
			errors += "IOError: " + e.text;
			trace("Io error"); 
			
		}
		
		private function onCancel(e:Event):void 
		{
			trace("Cancel");
		}
		
		private function onFileSelected(e:Event):void 
		{
			if (_fileRef.size <= IMG_SIZE_Bytes)
			{
				_fileRef.addEventListener(Event.COMPLETE, onLoadComplete);
				_fileRef.load();
			}
		}
		
		private function onLoadComplete(e:Event):void 
		{
			_fileRef.removeEventListener(Event.COMPLETE, onLoadComplete);
			_imgLoader = new Loader();
			_imgLoader.loadBytes(e.target.data);
			_imgLoader.contentLoaderInfo.addEventListener(Event.COMPLETE, completeLoadImage);
		}
		
		private function completeLoadImage(e:Event):void 
		{
			_imgLoader.contentLoaderInfo.removeEventListener(Event.COMPLETE, completeLoadImage);
			
			_content = e.target.content;
			_imgLoader = null;
			
			dispatchEvent(new Event(Event.COMPLETE));
		}
		
		public function Destroy():void
		{
			_fileRef.removeEventListener(Event.SELECT, onFileSelected);
			_fileRef.removeEventListener(Event.CANCEL, onCancel);
			_fileRef.removeEventListener(IOErrorEvent.IO_ERROR, onIOError);
			_fileRef.removeEventListener(SecurityErrorEvent.SECURITY_ERROR, onSecurityErr);
			_fileRef = null;
			_fileFilter = null;
		}
		
		public function get content():Object { return _content; }
		
	}

}